<template>
  <div class="information-container">
    <el-page-header
      content="信息管理"
      @back="router.back"
      style="margin-bottom: 16px"
    />
    
    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" class="search-form">
        <el-form-item label="信息内容">
          <el-input
            v-model="searchForm.message"
            placeholder="请输入信息内容"
            clearable
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="消息类型">
          <el-select
            v-model="searchForm.dictionaryid"
            placeholder="请选择"
            clearable
            style="width: 180px"
          >
            <el-option label="审核" :value="1" />
            <el-option label="入库" :value="2" />
            <el-option label="出库" :value="3" />
            <el-option label="库存" :value="4" />
            <el-option label="到期提醒" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="消息状态">
          <el-select
            v-model="searchForm.state"
            placeholder="请选择"
            clearable
            style="width: 180px"
          >
            <el-option label="未读" :value="false" />
            <el-option label="已读" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch" icon="Search">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <div class="action-buttons">
        <el-button @click="handleBatchDelete" type="danger">删除</el-button>
        <el-button @click="excelinformation" type="success">导出</el-button>
      </div>
      
      <el-table
        :data="paginatedData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" :index="getIndex" />
        <el-table-column prop="logMessage" label="消息内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="dictionaryId" label="消息类型" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.dictionaryId === 1" type="warning">审核</el-tag>
            <el-tag v-else-if="scope.row.dictionaryId === 2" type="success">入库</el-tag>
            <el-tag v-else-if="scope.row.dictionaryId === 3" type="primary">出库</el-tag>
            <el-tag v-else-if="scope.row.dictionaryId === 4" type="info">库存</el-tag>
            <el-tag v-else-if="scope.row.dictionaryId === 5" type="danger">到期提醒</el-tag>
            <span v-else>{{ scope.row.dictionaryId }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="logState" label="消息状态" width="100">
          <template #default="scope">
            <el-tag v-if="!scope.row.logState" type="danger">未读</el-tag>
            <el-tag v-else type="success">已读</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="logDateTime" label="接收时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.logDateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="scope">
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <div class="pagination-info">总{{ filteredData.length }}条</div>
        <el-pagination
          v-model:current-page="page.pageindex"
          v-model:page-size="page.pagesize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredData.length"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
        <el-select
          v-model="page.pagesize"
          style="width: 100px; margin-left: 10px"
          @change="handleSizeChange"
        >
          <el-option label="10条/页" :value="10" />
          <el-option label="20条/页" :value="20" />
          <el-option label="50条/页" :value="50" />
          <el-option label="100条/页" :value="100" />
        </el-select>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Delete } from '@element-plus/icons-vue'
import myaxios from '@/http/MyAxios'
import moment from 'moment'
import { useRouter } from 'vue-router'

const router = useRouter()

// 查询表单
const searchForm = reactive({
  message: '',
  dictionaryid: null as number | null,
  state: null as boolean | null
})

// 表格数据
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])
const loading = ref(false)

// 分页
const page = reactive({
  pageindex: 1,
  pagesize: 10
})

// 消息类型映射
const messageTypeMap: Record<number, string> = {
  1: '审核',
  2: '入库',
  3: '出库',
  4: '库存',
  5: '到期提醒'
}

// 过滤后的数据
const filteredData = computed(() => {
  let result = [...tableData.value]
  
  // 按信息内容过滤
  if (searchForm.message) {
    result = result.filter(item => 
      item.logMessage && item.logMessage.includes(searchForm.message)
    )
  }
  
  // 按消息类型过滤
  if (searchForm.dictionaryid !== null) {
    result = result.filter(item => item.dictionaryId === searchForm.dictionaryid)
  }
  
  // 按消息状态过滤
  if (searchForm.state !== null) {
    result = result.filter(item => item.logState === searchForm.state)
  }
  
  // 按时间倒序排序
  result.sort((a, b) => {
    const timeA = new Date(a.logDateTime).getTime()
    const timeB = new Date(b.logDateTime).getTime()
    return timeB - timeA
  })
  
  return result
})

// 分页后的数据
const paginatedData = computed(() => {
  const start = (page.pageindex - 1) * page.pagesize
  const end = start + page.pagesize
  return filteredData.value.slice(start, end)
})

// 计算序号
const getIndex = (index: number) => {
  return (page.pageindex - 1) * page.pagesize + index + 1
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params: any = {
      message: searchForm.message || undefined,
      dictionaryid: searchForm.dictionaryid || undefined,
      state: searchForm.state !== null ? searchForm.state : undefined
    }

    const res = await myaxios({
      url: '/api/Information/GetInformation',
      method: 'get',
      params
    })

    if (res.data && res.data.code === 200) {
      tableData.value = res.data.data || []
      // 重置到第一页
      if (page.pageindex > 1 && paginatedData.value.length === 0) {
        page.pageindex = 1
      }
    } else {
      ElMessage.error(res.data?.message || '查询失败')
    }
  } catch (error: any) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  page.pageindex = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.message = ''
  searchForm.dictionaryid = null
  searchForm.state = null
  page.pageindex = 1
  loadData()
}

// 删除
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认删除该消息吗？', '警告', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    const res = await myaxios({
      url: '/api/Information/DeleteInformation',
      method: 'put',
      params: { logId: row.logId }
    })

    if (res.data && res.data.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(res.data?.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的消息')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 条消息吗？`,
      '警告',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )

    const logIds = selectedRows.value.map((row: any) => row.logId).join(',')
    const res = await myaxios({
      url: '/api/Information/DeleteAllInformation',
      method: 'put',
      params: { logIds }
    })

    if (res.data && res.data.code === 200) {
      ElMessage.success('批量删除成功')
      selectedRows.value = []
      loadData()
    } else {
      ElMessage.error(res.data?.message || '批量删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  }
}
const excelinformation=()=>
{
  location.href='http://localhost:8080/api/Information/ImporeExcel'
}
// 分页大小变化
const handleSizeChange = () => {
  page.pageindex = 1
}

// 页码变化
const handlePageChange = () => {
  // 页码变化时不需要重新加载数据，因为使用的是计算属性
}

// 格式化时间
const formatDateTime = (dateTime: string | Date) => {
  if (!dateTime) return ''
  return moment(dateTime).format('YYYY-MM-DD HH:mm:ss')
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.information-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.table-card {
  margin-top: 10px;
}

.action-buttons {
  margin-bottom: 16px;
}

.action-buttons .el-button {
  margin-right: 10px;
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 10px 0;
}

.pagination-info {
  margin-right: 20px;
  color: #606266;
  font-size: 14px;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}

:deep(.el-pagination .el-pager li) {
  margin: 0 4px;
}

:deep(.el-pagination .el-pager li.is-active) {
  background-color: #67c23a;
  color: #fff;
}
</style>
